using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ScavengerHunt
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Camera camera;
        Menus menu;
        SpriteFont menuFont;
        SoundEffect soundEffect;
        Vector2 center;
#if !XBOX
        //Keyboard kb;
        MouseState mouse;
#endif

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            Components.Add(camera = new Camera(this));
            menu = new Menus(this);
            menu.Initialize();
            camera.SetProjection(Window.ClientBounds.Width,
                  Window.ClientBounds.Height);
            center = new Vector2(Window.ClientBounds.Width / 2, Window.ClientBounds.Height / 2);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Services.AddService(typeof(SpriteBatch), spriteBatch);
            menuFont = Content.Load<SpriteFont>("Menu");
            soundEffect = Content.Load<SoundEffect>("XACT\\Win\\Kerwghgg");

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState keyboardState = Keyboard.GetState();
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || keyboardState.IsKeyDown(Keys.Escape))
                this.Exit();
            // TODO: Add your update logic here
            //Sound Test
            if(keyboardState.IsKeyDown(Keys.F))
            {
                soundEffect.Play();
            }
            menu.Update(gameTime);
            camera.SetFrameInterval(gameTime);
            camera.Move(Move());
            camera.Strafe(Strafe());
            camera.SetView(ChangeView(gameTime));
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            //float radius = GetMaxMesRadius(whatamodel);
            //Components.Add(new triosImage(this));
            //Components.Add(new VoidBunny(this, camera));
            menu.Draw(gameTime);
            spriteBatch.Begin();
            spriteBatch.DrawString(menuFont, "Seconds:" + gameTime.TotalGameTime.Seconds.ToString(), Vector2.Zero, Color.Tomato);
            spriteBatch.DrawString(menuFont, "Milliseconds Elapsed:" + gameTime.ElapsedGameTime.Milliseconds.ToString(), new Vector2(0, 30), Color.Violet);
            spriteBatch.End();
            base.Draw(gameTime);
        }

        float Move()
        {
            KeyboardState kb = Keyboard.GetState();
            GamePadState gp = GamePad.GetState(PlayerIndex.One);
            float move = 0.0f;
            const float SCALE = 1.50f;

            // gamepad in use
            if (gp.IsConnected)
            {
                // left stick shifted left/right
                if (gp.ThumbSticks.Left.Y != 0.0f)
                    move = (SCALE * gp.ThumbSticks.Left.Y);
            }
            // no gamepad - use UP&DOWN or W&S
            else
            {
#if !XBOX
                if (kb.IsKeyDown(Keys.Up) || kb.IsKeyDown(Keys.W))
                    move = 1.0f * 10;  // Up or W - move ahead
                else if (kb.IsKeyDown(Keys.Down) || kb.IsKeyDown(Keys.S))
                    move = -1.0f; // Down or S - move back
#endif
            }
            return move;
        }

        float Strafe()
        {
            KeyboardState kb = Keyboard.GetState();
            GamePadState gp = GamePad.GetState(PlayerIndex.One);

            // using gamepad leftStick shifted left / right for strafe
            if (gp.IsConnected)
            {
                if (gp.ThumbSticks.Left.X != 0.0f)
                    return gp.ThumbSticks.Left.X;
            }
            // using keyboard - strafe with Left&Right or A&D
            else if (kb.IsKeyDown(Keys.Left) || kb.IsKeyDown(Keys.A))
                return -1.0f; // strafe left
            else if (kb.IsKeyDown(Keys.Right) || kb.IsKeyDown(Keys.D))
                return 1.0f;  // strafe right
            return 0.0f;
        }

        Vector2 ChangeView(GameTime gameTime)
        {
            const float SENSITIVITY = 250.0f;
            const float VERTICAL_INVERSION = -1.0f; // vertical view control
            // negate to reverse

            // handle change in view using right and left keys
            KeyboardState kbState = Keyboard.GetState();
            int widthMiddle = Window.ClientBounds.Width / 2;
            int heightMiddle = Window.ClientBounds.Height / 2;
            Vector2 change = Vector2.Zero;
            GamePadState gp = GamePad.GetState(PlayerIndex.One);

            if (gp.IsConnected == true) // gamepad on PC / Xbox
            {
                float scaleY = VERTICAL_INVERSION * (float)
                               gameTime.ElapsedGameTime.Milliseconds / 50.0f;
                change.Y = scaleY * gp.ThumbSticks.Right.Y * SENSITIVITY;
                change.X = gp.ThumbSticks.Right.X * SENSITIVITY;
            }
            else
            {
                // use mouse only (on PC)
#if !XBOX
                float scaleY = VERTICAL_INVERSION * (float)
                               gameTime.ElapsedGameTime.Milliseconds / 100.0f;
                float scaleX = (float)gameTime.ElapsedGameTime.Milliseconds / 400.0f;

                // get cursor position
                mouse = Mouse.GetState();

                // cursor not at center on X
                if (mouse.X != widthMiddle)
                {
                    change.X = mouse.X - widthMiddle;
                    change.X /= scaleX;
                }
                // cursor not at center on Y
                if (mouse.Y != heightMiddle)
                {
                    change.Y = mouse.Y - heightMiddle;
                    change.Y /= scaleY;
                }
                // reset cursor back to center
                Mouse.SetPosition(widthMiddle, heightMiddle);
#endif
            }
            return change;
        }

        private float GetMaxMeshRadius(Model m)
        {
            float radius = 0.0f;
            foreach (ModelMesh mm in m.Meshes)
            {
                if (mm.BoundingSphere.Radius > radius)
                {
                    radius = mm.BoundingSphere.Radius;
                }
            }
            return radius;
        }
        private void DrawModel(Model m, float radius, Matrix proj, Matrix view)
        {
            m.Draw(Matrix.CreateScale(1.0f / radius), view, proj);
        }
    }
}
